//
//  ViewController.swift
//  扫描Wi-Fi
//
//  Created by 郭颢源 on 2021/4/23.
//

import UIKit
import SystemConfiguration.CaptiveNetwork


class ViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        let ssid = getAllWiFiNameList()
        print("SSID: \(ssid)")
        
        let wifiInfo = getWifiInfo()
        print("SSID(WiFi名称): \(wifiInfo.0)")
        print("BSSID(Mac地址): \(wifiInfo.1)")
    }
    func getAllWiFiNameList() -> String {
        var ssid: String?
        if let interfaces = CNCopySupportedInterfaces() as NSArray? {
            for interface in interfaces {
                if let interfaceInfo = CNCopyCurrentNetworkInfo(interface as! CFString) as NSDictionary? {
                    ssid = interfaceInfo[kCNNetworkInfoKeySSID as String] as? String
                    print("****",ssid!)
                    break
                }
            }
        }
        return "ssid"
    }
    
    //获取 WiFi 信息
    func getWifiInfo() -> (ssid: String, mac: String) {
        if let cfas: NSArray = CNCopySupportedInterfaces() {
            for cfa in cfas {
                if let dict = CFBridgingRetain(
                    CNCopyCurrentNetworkInfo(cfa as! CFString)
                ) {
                    if let ssid = dict["SSID"] as? String,
                       let bssid = dict["BSSID"] as? String {
                        return (ssid, bssid)
                    }
                }
            }
        }
        return ("未知", "未知")
    }
    
    // 获取当前wifi名称
    
    func getWifiName() -> String? {
        
        let interfaces: CFArray! = CNCopySupportedInterfaces()
        
        if interfaces == nil { return nil }
        
        let if0: UnsafeRawPointer? = CFArrayGetValueAtIndex(interfaces, 0)
        
        if if0 == nil { return nil }
        
        let interfaceName: CFString = unsafeBitCast(if0!, to: CFString.self)
        
        let dictionary = CNCopyCurrentNetworkInfo(interfaceName) as NSDictionary?
        
        if dictionary == nil { return nil }
        
        return dictionary?[kCNNetworkInfoKeySSID as String] as? String
        
    }
    
    
}

